﻿using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;

namespace Bright.NetCore.Api.Middleware
{
    /// <summary>
    /// 自定义模型验证
    /// </summary>
    public class CustomModelValidator : IModelValidator
    {
        /// <summary>
        /// 重写自定义验证逻辑
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public IEnumerable<ModelValidationResult> Validate(ModelValidationContext context)
        {
            // 允许某些属性缺失
            return [];
        }

        // 注册自定义模型验证器
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(options =>
            {
                options.ModelValidatorProviders.Insert(0, new CustomModelValidatorProvider());
            });
        }
    }

    /// <summary>
    /// 自定义模型验证器提供程序
    /// </summary>
    public class CustomModelValidatorProvider : IModelValidatorProvider
    {
        /// <summary>
        /// 创建自定义模型验证器
        /// </summary>
        /// <param name="context"></param>
        public void CreateValidators(ModelValidatorProviderContext context)
        {
            foreach (var descriptor in context.Results)
            {
                descriptor.Validator = new CustomModelValidator();
            }
        }
    }
}
